import React , { useState,useEffect, useRef} from 'react';
import { Button, Form, Input,Select,InputNumber, Space, Tag, Tooltip, theme } from 'antd';
import { PlusOutlined,LoadingOutlined } from '@ant-design/icons';
import { Upload, message} from 'antd';
import { useNavigate } from 'react-router-dom';
import axios from '../../../../../utils/myAixos'
import "./add.scss"
const { TextArea } = Input;


//和上传有关的想法
const getBase64 = (img, callback) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
};
const AddClass=()=>{
    ///////////以下都是头像相关的
    const [loading] = useState(false);
    const [imageUrl, setImageUrl] = useState();

    const handleChange = (info) => {
        console.log('%c ======>>>>>>>>', 'color:orange;', 'info', info)
        //判断他的类型和大小
        const isJpgOrPng = info.file.type === 'image/jpeg' || info.file.type === 'image/png' || info.file.type === 'image/jpg';
        if (!isJpgOrPng) {
            return message.error('只能上传 jpeg/jpg/png 图片');
        }
        const isLt2M = info.file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
            return message.error('最大只能上传2M的图片');
        }
        //将文件对象转成base64的地址，img才能显示出来
        getBase64(info.file.originFileObj, (url) => {
            setImageUrl(url);
        });
    };
    const uploadButton = (
        <div>
            {loading ? <LoadingOutlined /> : <PlusOutlined />}
            <div
                style={{
                    marginTop: 8,
                }}
            >
                Upload
            </div>
        </div>
    );
    const customRequest = () => {
        console.log('customRequest 执行了')
    }
    //标签
    const { token } = theme.useToken();
  const [tags, setTags] = useState(['健身', '减肥', '燃脂']);
  const [inputVisible, setInputVisible] = useState(false);
  const [inputValue, setInputValue] = useState('');
  const [editInputIndex, setEditInputIndex] = useState(-1);
  const [editInputValue, setEditInputValue] = useState('');
  const inputRef = useRef(null);
  const editInputRef = useRef(null);
  useEffect(() => {
    if (inputVisible) {
      inputRef.current?.focus();
    }
  }, [inputVisible]);
  useEffect(() => {
    editInputRef.current?.focus();
  }, [inputValue]);
  const handleClose = (removedTag) => {
    const newTags = tags.filter((tag) => tag !== removedTag);
    console.log(newTags);
    setTags(newTags);
  };
  const showInput = () => {
    setInputVisible(true);
  };
  const handleInputChange = (e) => {
    setInputValue(e.target.value);
  };
  const handleInputConfirm = () => {
    if (inputValue && tags.indexOf(inputValue) === -1) {
      setTags([...tags, inputValue]);
    }
    setInputVisible(false);
    setInputValue('');
  };
  const handleEditInputChange = (e) => {
    setEditInputValue(e.target.value);
  };
  const handleEditInputConfirm = () => {
    const newTags = [...tags];
    newTags[editInputIndex] = editInputValue;
    setTags(newTags);
    setEditInputIndex(-1);
    setInputValue('');
  };
  const tagInputStyle = {
    width: 78,
    verticalAlign: 'top',
  };
  const tagPlusStyle = {
    background: token.colorBgContainer,
    borderStyle: 'dashed',
  };
  //保存
  //添加
    const onFinish = (values) => {
        console.log('Finish:', values);
        //第一步，得到一个formData盒子
        let myFormData = new FormData()
        //第二步，讲文件装到这个盒子里面去  组装数据
        console.log('2',values.myfile.file.originFileObj)
        // myFormData.append(内容的名字，内容)  如果这个内容是一个文件，放的就是文件对象
        myFormData.append('myFile',values.myfile.file.originFileObj)
        myFormData.append('c_name',values.c_name)
        myFormData.append('c_number',values.c_number)
        myFormData.append('c_teacher',values.c_teacher)
        myFormData.append('c_time',values.c_time)
        myFormData.append('c_introduce',values.c_introduce)
        // 第三步  发请求
        axios({
            url:'/addCourse',
            method:'post',
            data:myFormData
        }).then(res => {
            console.log('添加学生的结果', res)
            if(res.status === 200){
                message.success('上传成功')
               
            }else{
                message.error('上传失败')
            }
        }).catch(err => {
            console.log('添加学生失败的结果', err)
        })
    };
    const onFinishFailed = (values) => {
        console.log('onFinishFailed:', values);
    }
     const navigate = useNavigate();
     const handleBack=()=>{
         navigate(-1)
     }
    return(
        <div  className={"box1"}>
          <header className={"head"}>
            课程添加
          </header>
            {/* 表单 */}
          <div  className={"content"}>
          <Form
                    name="basic"
                    labelCol={{ span: 10}}
                    wrapperCol={{ span: 14}}
                    layout="horizontal"
                    style={{
                        maxWidth: 600,
                    }}
                    onFinish={onFinish}
                    onFinishFailed={onFinishFailed}
                >
                    <Form.Item
                        label="课程名称"
                        name="c_name"
                        className={"test"}
                        rules={[{ required: true, message: '请输入你的课程名称' }]}
                    >
                        <Input  />
                    </Form.Item>
                    {/* 上传图片 */}
                  <Form.Item
                        label="课程图片"
                        name="myfile"
                        rules={[{ required: true, message: '头像必选' }]}                                
                    >  
                          <Upload
                        name="avatar"
                        listType="picture-card" 
                        className="avatar-uploader"
                        showUploadList={false}
                        action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
                        onChange={handleChange}
                        customRequest={customRequest}                          
                    >
                        {imageUrl ? (
                            <img
                                src={imageUrl}
                                alt="avatar"
                                style={{
                                    width: '100%',
                                }}
                            />
                        ) : (
                            uploadButton
                        )}
                    </Upload> 
                    </Form.Item>
                    <Form.Item
                        label="课程时长"
                        name="c_time"
                        rules={[{ required: true, message: '请输入你的课程时长' }]}
                    >
                        <Input />
                    </Form.Item>
                    <Form.Item  label="可预约人数"
                        name="c_number"
                        rules={[{ required: true, message: '请输入可预约人数' }]}
                        >
                        <div className={"tp"}>
                           <InputNumber  style={{float:"left"}}/>
                        </div>     
                    </Form.Item>
                        <Form.Item
                        label="教练"
                        rules={[{ required: true, message: '请输入课程教练' }]} 
                        name="c_teacher"
                    >
                        <Select
                            defaultValue="请选择课程教练"
                            style={{
                                width: 120,
                                float:"left",
                            }}
                            options={[
                                {
                                    value: '小明',
                                    label: '小明',
                                },
                                {
                                    value: '小张',
                                    label: '小张',
                                }
                            ]}
                        />

                    </Form.Item>
                    <Form.Item
                        label="课程标签"
                        rules={[{ required: true, message: '请输入课程标签' }]}
                    >
                    <div className={"tb"}>
                    <Space size={[0, 8]} wrap>
                    <Space size={[0, 8]} wrap>
                        {tags.map((tag, index) => {
                        if (editInputIndex === index) {
                            return (
                            <Input
                                ref={editInputRef}
                                key={tag}
                                size="small"
                                style={tagInputStyle}
                                value={editInputValue}
                                onChange={handleEditInputChange}
                                onBlur={handleEditInputConfirm}
                                onPressEnter={handleEditInputConfirm}
                            />
                            );
                        }
                        const isLongTag = tag.length > 20;
                        const tagElem = (
                            <Tag
                            key={tag}
                            closable={index !== 0}
                            style={{
                                userSelect: 'none',
                            }}
                            onClose={() => handleClose(tag)}
                            >
                            <span
                                onDoubleClick={(e) => {
                                if (index !== 0) {
                                    setEditInputIndex(index);
                                    setEditInputValue(tag);
                                    e.preventDefault();
                                }
                                }}
                            >
                                {isLongTag ? `${tag.slice(0, 20)}...` : tag}
                            </span>
                            </Tag>
                        );
                        return isLongTag ? (
                            <Tooltip title={tag} key={tag}>
                            {tagElem}
                            </Tooltip>
                        ) : (
                            tagElem
                        );
                        })}
                    </Space>
                    {inputVisible ? (
                        <Input
                        ref={inputRef}
                        type="text"
                        size="small"
                        style={tagInputStyle}
                        value={inputValue}
                        onChange={handleInputChange}
                        onBlur={handleInputConfirm}
                        onPressEnter={handleInputConfirm}
                        />
                    ) : (
                        <Tag style={tagPlusStyle} onClick={showInput}>
                        <PlusOutlined /> 添加新标签
                        </Tag>
                    )}
                    </Space>

                    </div>
                    </Form.Item>
                    <Form.Item    label="课程介绍"
                        name="c_introduce"
                        rules={[{ required: true, message: '请输入课程介绍' }]}>
                       <TextArea rows={4} />
                    </Form.Item>
                    <Form.Item>
                        <Button type="primary" htmlType="submit"  onClick={handleBack} style={{float:"right"}}>
                            保存
                        </Button>
                    </Form.Item>
                </Form>
          </div>
        
        </div>
    )
}
export default AddClass